package soccerBet.project.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import soccerBet.project.betfair.exchange.BFExchangeServiceStub.BetTypeEnum;
import soccerBet.project.objects.*;
import soccerBet.project.ruleEngine.ApostaRule;
import soccerBet.project.utils.*;

public class InfoPrecosDAO {
	

	
	
	public void guardarInfoPrecos(Precos preco, ApostaRule rule){
	       

		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
		InfoPrecos ip = new InfoPrecos(preco, new Sentido(rule.getTipo()==BetTypeEnum.B ? 1 : 2),
				calculaGanho(rule.getTipo(),rule),calculaRisco(rule.getTipo(),rule),rule.getPrice(),preco.getData(),0,rule.getIdJogo());		
		
		session.saveOrUpdate(ip);

		// Commit the transaction
		session.getTransaction().commit();
		
		
		session.close();
	 
		
	 }
	
	
	public void guardarInfo(InfoPrecos infoPreco){
	       

		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		
			
		session.saveOrUpdate(infoPreco);

		// Commit the transaction
		session.getTransaction().commit();
		
		
		session.close();
	 
		
	 }
	
	
	 private Double calculaGanho(BetTypeEnum tipo, ApostaRule rule) {
		// TODO Auto-generated method stub
		if(tipo==BetTypeEnum.B){
			return rule.getSize()*(rule.getPrice()-1);
		}else{
			return rule.getSize();
		}
	}

	private Double calculaRisco(BetTypeEnum tipo, ApostaRule rule) {
		// TODO Auto-generated method stub
		
		if(tipo==BetTypeEnum.B){
			return rule.getSize();
		}else{
			return rule.getSize()*(rule.getPrice()-1);
		}
	}

	public List<InfoPrecos> getInfoPrecoByJogo(Integer idJogo) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		
		List<InfoPrecos> InfoPrecoList = (List<InfoPrecos>)   session.
		createQuery("select ip from InfoPrecos as ip where ip.idJogo = ?")
		.setInteger(0, idJogo).list();
		
		
		
		session.close();
		
		return InfoPrecoList;

	 }


	public String getApostaByInfoPreco(Integer idInfoPrecos) {
		// TODO Auto-generated method stub
		
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		
		Apostas aposta = (Apostas)  session.
		createQuery("select a from Apostas as a join a.runners as r join r.precoses as  p join p.infoPrecoses as ip  where ip.idInfoPrecos = ?")
		.setInteger(0, idInfoPrecos).uniqueResult();
		
		
		session.close();
		
		return aposta.getApostaSid();
		
	}
	
	
	public List<InfoPrecos> getInfoPrecoByDate() {

		Session session = HibernateUtil.getSessionFactory().openSession();		
		
		List<InfoPrecos> InfoPrecoList = (List<InfoPrecos>)   session.
		createQuery("select ip from InfoPrecos as ip").list();
		session.close();
		
		return InfoPrecoList;

	 }
	

	    
	}